<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="formContainer">
        <el-button class="buttons" @click="handleCreate"> 添加</el-button>
      </div>

      <div class="formContainer">
        <label class="filterLabel">关键词:</label>
        <el-input v-model="listQuery.keyword" placeholder="请输入关键词" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <label class="filterLabel">状态:</label>
        <el-select v-model="listQuery.isshow" class="search-select" clearable placeholder="请选择">
          <el-option label="显示" :value="1" />
          <el-option label="隐藏" :value="2" />
        </el-select>
        <el-button class="buttons" @click="handleFilter"> 搜索 </el-button>
      </div>
    </div>
    <el-table :key="tableKey" :data="list" style="width: 100%;" :header-cell-style="{background:'#ebebeb',height:'#54px'}" @sort-change="sortChange">
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" prop="name" align="center" sortable="custom">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="广告位置" prop="name" align="center" sortable="custom">
        <template slot-scope="{row}">
          <span>{{ row.adverts_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="链接地址" prop="name" align="center" sortable="custom">
        <template slot-scope="{row}">
          <a
            class="link-color"
            :href="row.jump_url"
            target="_blank"
          >{{ row.jump_url }}</a>
        </template>
      </el-table-column>
      <el-table-column label="预览图" prop="image" align="center" sortable="custom">
        <template slot-scope="{row}">
          <el-image :src="row.image" class="table-img" :preview-src-list="[row.image]" />
        </template>
      </el-table-column>
      <el-table-column label="添加时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.addtime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center">
        <template slot-scope="{row}">
          <span>{{ row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" min-width="150px">
        <template slot-scope="{row}">
          <el-tag>{{ row.isshow_name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            confirm-button-text="好的"
            cancel-button-text="不用了"
            icon="el-icon-info"
            icon-color="red"
            title="删除后不可以恢复，确定删除吗？"
            @onConfirm="handleDelete(row,$index)"
          >
            <el-button
              slot="reference"
              size="mini"
              type="danger"
            >删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.per_page" @pagination="getList" />
    <!-- 编辑、 添加弹框表单 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="rows" label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
        <el-form-item label="名称" prop="text">
          <el-input v-model="rows.text" placeholder="请输入名称" />
        </el-form-item>
        <!-- <el-form-item label="广告id" prop="adverts_id">
          <el-select v-model="rows.adverts_id" placeholder="请选择" @change="adChang">
            <el-option
              v-for="(item,index) in cateLists"
              :key="index"
              :value="item.id"
              :label="item.name"
            />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="链接地址" prop="name">
          <el-input v-model="rows.jump_url" placeholder="请输入链接地址" />
        </el-form-item> -->
        <el-form-item label="图片"><span>{{ cateDetail.content }}</span>
          <uploadImg v-model="rows.image_url_local" />
        </el-form-item>
        <!-- <el-form-item label="是否显示">
          <el-radio-group v-model="rows.isshow">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="排序" prop="realname">
          <el-input v-model="rows.sort" type="number" placeholder="排序" />
          <span class="tips">越小越靠前</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">          取消        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, del, add, rows, edit, getInfos } from '@/api/cardsImg'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import uploadImg from '@/components/Upload/uploadImg'
import { notifySuccess } from '@/utils/message'

export default {
  name: 'AttachmentIndex',
  components: { Pagination, uploadImg },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        per_page: 15,
        importance: null,
        keyword: null,
        type: null,
        sort: 'id',
        order: 'desc',
        filter: [],
        op: []
      },
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      rows: {
        id: null,
        text: '',
        image_url_local: '',
        // isshow: 1,
        sort: 100
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑数据',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        jump_url: [{ required: true, message: '请输入链接地址', trigger: 'blur' }],
        text: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        adverts_id: [{ required: true, message: '请选择广告位置', trigger: 'blur' }]
      },
      cateLists: {},
      downloadLoading: false,
      cateDetail: { content: '' }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表数据
    getList() {
      var that = this
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        setTimeout(() => {
          that.listLoading = false
        }, 1.5 * 1000)
      })
    },
    // 搜索按钮提交
    searchSumit(e) {
      this.listQuery.filter = e.filter
      this.listQuery.op = e.op
      this.listQuery.page = 1
      this.getList()
    },
    // 搜索查询
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      notifySuccess('', '操作成功')
      row.status = status
    },
    // 排序
    sortChange(data) {
      const { prop, order } = data
      this.listQuery.sort = prop
      this.sortByID(order)
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.order = 'ASC'
      } else {
        this.listQuery.order = 'DESC'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.rows = {
        id: null,
        text: null,
        adverts_id: null,
        jump_url: null,
        image_url_local: null,
        isshow: 1,
        sort: 100
      }
    },
    getCates() {
      getInfos().then(res => {
        this.cateLists = res.data
      })
    },
    handleCreate() {
      // this.getCates()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.resetTemp()
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          add(this.rows).then(res => {
            //  this.list.unshift(this.rows)
            this.dialogFormVisible = false
            notifySuccess(res.msg || '添加成功')
            this.resetTemp()
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.getCates()
      rows(row.id).then(res => {
        this.rows = res.data
        this.rows.image = res.data.image.url
        this.adChang(res.data.adverts_id)
      })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.rows)
          edit(tempData.id,
            tempData.name,
            tempData.adverts_id,
            tempData.jump_url,
            tempData.image,
            tempData.isshow,
            tempData.sort).then(res => {
            this.list.findIndex(v => v.id === this.rows.id)
            // this.list.splice(index, 1, this.rows)
            this.dialogFormVisible = false
            this.getList()
            this.resetTemp()
            notifySuccess(res.msg || '编辑功')
          })
        }
      })
    },
    // 删除附件
    handleDelete(row, index) {
      del(row.id).then(res => {
        this.list.splice(index, 1)
        notifySuccess(res.msg || '删除成功')
      })
    },
    typeChange(e) {
      console.log(e)
    },
    adChang(e) {
      this.cateLists.forEach((element, index) => {
        if (e === element.id) {
          this.cateDetail = element
        }
      })
    }
  }
}
</script>
<style scoped>
.table-img{height: 50px;min-width: 50;}
.link-color{color: #409eff;}
</style>
